import { _decorator, Component, Vec3, RigidBody, v3, PhysicsSystem } from 'cc';
import { Battle } from '../Battle';
const { ccclass, property } = _decorator;

@ccclass('PhysicsParabola')
export class PhysicsParabola extends Component {

    targetNode; // 目标位置节点

    height: number = 5; // 抛物线最大高度

    private _startPos: Vec3 = new Vec3();
    private _endPos: Vec3 = new Vec3();
    private _rigidBody: RigidBody | null = null;

    onLoad() {
        
    }

    start() {
        // this.scheduleOnce(function(){
        // this._rigidBody = this.getComponent(RigidBody);
        // if (!this._rigidBody) {
        //     console.error('请添加RigidBody组件');
        //     return;
        // }
        
        // if (!this.targetNode) {
        //     console.error('请设置目标节点');
        //     return;
        // }
        
        // this.targetNode = this.node.parent.getChildByName("anim");
        // this._startPos = this.node.worldPosition.clone();
        // const playerWorldPos = this.node.parent.getChildByName("anim").worldPosition.clone();
        // this._endPos = playerWorldPos.clone();

        // this.launch();
        // }.bind(this), 3);
        
    }

    // 计算发射速度
    calculateLaunchVelocity(): Vec3 {
        const horizontalDistance = Math.sqrt(
            Math.pow(this._endPos.x - this._startPos.x, 2) +
            Math.pow(this._endPos.z - this._startPos.z, 2)
        );
        
        const verticalDistance = this._endPos.y - this._startPos.y;
        
        // 计算初始速度
        const g = -9.8; // 重力加速度
        const vy = Math.sqrt(2 * g * this.height);
        const time = (vy + Math.sqrt(vy * vy - 2 * g * verticalDistance)) / -g;
        
        const vx = horizontalDistance / time;
        
        // 计算方向向量
        const direction = new Vec3(
            this._endPos.x - this._startPos.x,
            0,
            this._endPos.z - this._startPos.z
        ).normalize();
        
        // 合成速度向量
        return v3(
            direction.x * vx,
            vy,
            direction.z * vx
        );
    }

    // 发射物体
    launch() {
        if (!this._rigidBody) return;
        
        // 重置位置
        this._rigidBody.setLinearVelocity(Vec3.ZERO);
        this._rigidBody.setAngularVelocity(Vec3.ZERO);
        this.node.setWorldPosition(this._startPos);
        
        // 计算并设置速度
        const velocity = this.calculateLaunchVelocity();
        this._rigidBody.setLinearVelocity(velocity);
    }
}